/*
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
 * distributed with this file and available online at
 * http://www.ja-sig.org/products/cas/overview/license/
 */
package org.jasig.cas.ticket.registry;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import org.jasig.cas.ticket.Ticket;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Implementation of the TicketRegistry that is backed by a ConcurrentHashMap.
 * 
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 3.0
 */

/**
 * lgw 2016-11-16
 * 为能让sso实现集群部署，必须将Ticket 实现各节点共享
 * 实现方法，将Ticket 存入session中，集群部署时配置session共享
 */
public final class DefaultTicketRegistry0 extends AbstractTicketRegistry {

    /** A HashMap to contain the tickets. */
    private  Map<String, Ticket> cache;
    
    private  int initialCapacity =0;
    private  float loadFactor =0;
    private  int concurrencyLevel =0;
    
    public DefaultTicketRegistry0() {
        this.cache = new ConcurrentHashMap<String, Ticket>();
    }
    
    /**
     * Creates a new, empty registry with the specified initial capacity, load
     * factor, and concurrency level.
     * 
     * @param initialCapacity - the initial capacity. The implementation
     * performs internal sizing to accommodate this many elements.
     * @param loadFactor - the load factor threshold, used to control resizing.
     * Resizing may be performed when the average number of elements per bin
     * exceeds this threshold.
     * @param concurrencyLevel - the estimated number of concurrently updating
     * threads. The implementation performs internal sizing to try to
     * accommodate this many threads.
     */
    public DefaultTicketRegistry0(int initialCapacity, final float loadFactor, final int concurrencyLevel) {
        this.cache = new ConcurrentHashMap<String, Ticket>(initialCapacity, loadFactor, concurrencyLevel);
        this.initialCapacity = initialCapacity;
        this.loadFactor = loadFactor;
        this.concurrencyLevel = concurrencyLevel;
    }
    
    /**
     * @throws IllegalArgumentException if the Ticket is null.
     */
	public void addTicket(final Ticket ticket) {
        Assert.notNull(ticket, "ticket cannot be null");

        if (log.isDebugEnabled()) {
            log.debug("Added ticket [" + ticket.getId() + "] to registry.");
        }
       
        this.cache.put(ticket.getId(), ticket);
        //将ticket存入session
        HttpServletRequest request  = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute("TicketCaChe", this.cache);
        String path = request.getServerName()+":"+request.getServerPort();
        System.out.println("======add===path========="+path);
        System.out.println("======add===ticketCaChe========="+this.cache);
        System.out.println("=======sessionId======="+request.getSession().getId());
    }

    @SuppressWarnings("unchecked")
	public Ticket getTicket(final String ticketId) {
        if (ticketId == null) {
            return null;
        }

        if (log.isDebugEnabled()) {
            log.debug("Attempting to retrieve ticket [" + ticketId + "]");
        }
//        final Ticket ticket = this.cache.get(ticketId);
       //将ticket从session取出
        HttpServletRequest request  = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, Ticket> ticketCaChe = (Map<String, Ticket>) request.getSession().getAttribute("TicketCaChe");
       
        String path = request.getServerName()+":"+request.getServerPort();
        System.out.println("======get===path========="+path);
        System.out.println("======get===ticketCaChe========="+ticketCaChe);
        System.out.println("=======sessionId======="+request.getSession().getId());
        if(ticketCaChe==null||ticketCaChe.size()==0){
        	System.out.println("======get===ticketCaChe======new===start=====this.cache="+this.cache);
//        	this.cache = creatgetDefaultTicketRegistry(this.initialCapacity,this.loadFactor,this.concurrencyLevel);
        	ticketCaChe = this.cache;
        	 System.out.println("======get===ticketCaChe======new==="+ticketCaChe);
        	 System.out.println("======get===ticketCaChe======new===end======");
        	request.getSession().setAttribute("TicketCaChe", this.cache);
        	
        }
        final Ticket ticket = ticketCaChe.get(ticketId);
        if (ticket != null) {
            log.debug("Ticket [" + ticketId + "] found in registry.");
        }

        return ticket;
    }

    private Map<String, Ticket>  creatgetDefaultTicketRegistry(int initialCapacity,
			float loadFactor, int concurrencyLevel) {
    	 Map<String, Ticket> ticketCaChe = new ConcurrentHashMap<String, Ticket>(initialCapacity, loadFactor, concurrencyLevel);
		return ticketCaChe;
	}

	@SuppressWarnings("unchecked")
	public boolean deleteTicket(final String ticketId) {
        if (ticketId == null) {
            return false;
        }
        if (log.isDebugEnabled()) {
            log.debug("Removing ticket [" + ticketId + "] from registry");
        }

//        return (this.cache.remove(ticketId) != null);
//      将ticket从session取出
        HttpServletRequest request  = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, Ticket> ticketCaChe = (Map<String, Ticket>) request.getSession().getAttribute("TicketCaChe");
        String path = request.getServerName()+":"+request.getServerPort();
        System.out.println("======del===path========="+path);
        System.out.println("======del===ticketCaChe========="+this.cache);
        System.out.println("=======sessionId======="+request.getSession().getId());
        
        return (ticketCaChe.remove(ticketId) != null);
    }

	public Collection<Ticket> getTickets() {
        return Collections.unmodifiableCollection(this.cache.values());
    }
	
	

}
